package com.fkframe.codegener.ui.view;

import heip.generator.entity.ColumnClazz;
import heip.generator.entity.EntityTable;
import heip.generator.entity.PropEditor;
import heip.generator.entity.PropEditor.EditType;
import heip.generator.entity.TableClazz;
import heip.generator.entity.ValidateRule;
import heip.generator.generer.ActionGenerator;
import heip.generator.generer.EntityGenerator;
import heip.generator.generer.FlexGenerator;
import heip.generator.generer.ServiceDaoGenerator;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

import cn.org.rapid_framework.generator.GeneratorProperties;

import com.fkframe.codegener.ui.EETSoftFrame;

/**
 * 双层表生成机制
 * 
 * @author AGUU
 * 
 */
public class TwoTableGenerView extends CommonView {
	private JTextField txtModule;
	private JTextField txtTable;
	private JComboBox entityType;
	private JCheckBox chkPageable;
	private EETSoftFrame parentFrame;

	private JButton btnLoad;
	private JButton btnGener;
	private JPanel panel;
	private JPanel mainPanel;
	private JViewport jViewport;
	private JTable table;
	private JTable subtable;
	JScrollPane scrollPane;

	private TableClazz tableClazz;
	private JPanel panel_1;
	private JButton button;

	public TwoTableGenerView(EETSoftFrame parent, JPanel mainPanel,
			JViewport jViewport) {
		this.parentFrame = parent;
		this.mainPanel = mainPanel;
		this.jViewport = jViewport;

		// 1主面板
		mainPanel.setPreferredSize(new Dimension(parentFrame
				.getMinMainBoardWidth(), 500));
		mainPanel.removeAll();
		mainPanel.repaint();
		setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
		// setLayout(new FlowLayout(FlowLayout.CENTER, 1, 1));
		// this.mainPanel.setSize(700, 500);
		panel = new JPanel();
		panel.setLayout(new FlowLayout(FlowLayout.CENTER, 1, 1));

		JPanel panel_2 = new JPanel();
		panel_2.setLayout(new GridLayout(0, 4, 10, 10));

		// 模块
		panel_2.add(new JLabel("模块名(ex:cm.tb):"));
		txtModule = new JTextField();
		txtModule.setColumns(10);
		panel_2.add(txtModule);

		// 表名
		panel_2.add(new JLabel("表名(必输):"));

		txtTable = new JTextField();
		panel_2.add(txtTable);
		txtTable.setColumns(10);

		panel_2.add(new JLabel("单表类型 :"));
		entityType = new JComboBox(new Object[] { "基本" });
		panel_2.add(entityType);

		chkPageable = new JCheckBox("是否分页", true);
		panel_2.add(chkPageable);

		panel.add(panel_2);
		add(panel);
		add(Box.createVerticalStrut(10));

		panel_2.add(new JLabel(""));

		JButton btnNewButton = new JButton("1)加载表");
		panel_2.add(btnNewButton);
		btnNewButton.addActionListener(this);

		btnLoad = new JButton("2)生成");
		panel_2.add(btnLoad);
		btnLoad.addActionListener(this);

		// 3 主表属性设置
		scrollPane = new JScrollPane();
		table = renderColumnEditTable();
		scrollPane.setViewportView(table);
		scrollPane.setSize(600, 450);
		add(scrollPane);

		// 2子表列表
		JScrollPane subscrollPane = new JScrollPane();
		LinkedHashMap<String, String> subcolumnMap = new LinkedHashMap<String, String>();
		subcolumnMap.put("seq", "序号");
		subcolumnMap.put("tableName", "子表表名");
		subcolumnMap.put("fkCol", "外键字段");
		// subcolumnMap.put("Button", "配置");
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 4; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("seq", i + 1);
			map.put("tableName", "");
			map.put("fkCol", "");
			// map.put("Button", new JButton("加载"));
			data.add(map);
		}

		SimplePropTableModel subtableModel = new SimplePropTableModel();
		subtableModel.setColumnMap(subcolumnMap);
		subtableModel.setData(data);
		subtableModel.setEditAbleProp(new String[] { "tableName", "fkCol" });
		this.subtable = new JTable(subtableModel);

		// table.setDefaultRenderer(JButton.class, new ComboBoxCellRenderer());
		// subtable.getColumn(subtableModel.getColumnNameByKey("Button")).setCellRenderer(
		// new ComboBoxCellRenderer());
		subtable.getColumnModel().getColumn(1).setPreferredWidth(200);
		subtable.getColumnModel().getColumn(2).setPreferredWidth(200);
		
		subtable.setAutoscrolls(true);
		subtable.setFocusable(false);
		subtable.setCellSelectionEnabled(true);
		subtable.setColumnSelectionAllowed(false);
		subtable.setRowHeight(25);
		subtable.setAutoResizeMode(0);
		
		
		subscrollPane.setViewportView(subtable);
		subscrollPane.setSize(600, 400);
		add(subscrollPane);

		/*
		 * subtable.addMouseListener(new MouseAdapter(){ public void
		 * mouseClicked(MouseEvent e) { System.out.println("table"); int row =
		 * table.getSelectedRow(); int column = table.getSelectedColumn();
		 * System.out.println("row="+row+":"+"column="+column); if(column==4){
		 * System.out.println(((JButton)table.getValueAt(row,
		 * column)).getText()); } } });
		 */

	}

	public void setSubButtonEditColumn(TableColumn column) {
		JButton editButton = new JButton("加载子表");
		editButton.setFocusPainted(false);
		editButton.addActionListener(this);
		TableColumnModel columnModel = table.getColumnModel();
		// column.setCellEditor(new DefaultCellEditor(editButton));
		editButton.addActionListener(this);
	}

	public void reloadColumnPanel2() {
		// 刷新数据代码
		// 定义Vector 类型变量tmprow，colVec，并且赋值，就象上面那样，这里不重复了
		SimplePropTableModel model = (SimplePropTableModel) table.getModel();

		String tableName = txtTable.getText();
		tableClazz = new TableClazz(tableName);
		int columnSize = tableClazz.getColumns().size();

		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < columnSize; i++) {
			ColumnClazz col = tableClazz.getColumns().get(i);
			// 忽略掉ID
			if (col.isPk())
				continue;

			Map<String, Object> map = new HashMap<String, Object>();
			map.put("seq", i + 1);
			map.put("name", col.getName());
			map.put("cnName", col.getCnName());

			map.put("isQuery", false);
			map.put("isTable", true);
			map.put("isEdit", true);
			if (col.getJavaType().equals("Long")
					&& (col.getColumnName().indexOf("Id") != -1)) {
				map.put("editType", EditType.DIALOG.getName());
				// map.put("editRule", "");
			} else if (col.getColumnName().equals("remark")) {
				map.put("editType", EditType.TEXTAREA.getName());
			} else if (col.getJavaType().equals("Date")) {
				map.put("editType", EditType.DATE.getName());
			} else {
				map.put("editType", EditType.TEXTINPUT.getName());
				// map.put("editRule", "");
			}

			map.put("validateType1", "");
			map.put("validateRule1", "");

			/*
			 * map.put("validateType2",""); map.put("validateRule2", "");
			 */

			// map.put("validateType3","");
			// map.put("validateRule3", "");

			data.add(map);
		}
		model.setData(data);
		table.setModel(model);

		// table.validate();
		// table.repaint();
		SwingUtilities.updateComponentTreeUI(table);
	}

	public void getTableValue(){
		List<Map<String,Object>> data = ((SimplePropTableModel)table.getModel()).getTableData();
		for(Map<String,Object> row :data){
			String columnName = (String)row.get("name");
			String columnCnName = (String) row.get("cnName");
			boolean isQuery = (Boolean)row.get("isQuery");
			boolean isTable = (Boolean)row.get("isTable");
			boolean isEdit = (Boolean)row.get("isEdit");
			
			String validateTypeName1 = (String) row.get("validateType1"); 
			String validateRule1 = null;
//					(String) row.get("validateRule1");
			/*String validateTypeName2 = (String) row.get("validateType2"); 
			String validateRule2 = (String) row.get("validateRule2");*/
			//String validateTypeName3 = (String) row.get("validateType3"); 
			//String validateRule3 = (String) row.get("validateRule3");
			String editType=(String)row.get("editType");
			
			for(ColumnClazz col:this.tableClazz.getColumns()){
				if(col.getPropName().equals(columnName)){
					col.setPropCnName(columnCnName);
					col.setQueryCol(isQuery);
					col.setTableCol(isTable);
					col.setEditCol(isEdit);
					
					col.clearRule();//清空规则
					//校验规则
					ValidateRule rule = buildValidateRule(validateTypeName1, validateRule1); 
					if(rule!=null)col.addValidateRule(rule);
					/*ValidateRule rule2 = buildValidateRule(validateTypeName2, validateRule2); 
					if(rule2!=null)col.addValidateRule(rule2);*/
					
					if(editType!=null){
						PropEditor e = buildEditor(editType, null);
						col.setPropEditor(e);
					}
					
					//ValidateRule rule3 = buildValidateRule(validateTypeName3, validateRule3); 
					//if(rule3!=null)col.addValidateRule(rule3);
				}
			}
			
		}
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// btnGener.setEnabled(false);
		if (e.getActionCommand().indexOf("加载") != -1) {
			String moduleName = txtModule.getText();
			String tableName = txtTable.getText();
			reloadColumnPanel2();
			return;
		}
		getTableValue();
		doGenerAction();
	}
	
	 
	public void doGenerAction() {
		try {
			String tableName = txtTable.getText();
			String moduleName = txtModule.getText();
			moduleName = GenerUtil.generModuleName(moduleName, tableName);
			String modelType= (String) this.entityType.getSelectedItem();
			boolean pageable = this.chkPageable.isSelected();
			//参数准备
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("modelType", modelType);
			params.put("pageable",pageable);
			
			params.put("editpage","dialog");//编辑界面使用不同页面
			params.put("detailpage","dialog");//明细页面使用不同页面调整
			
			//1 生成
			if(this.tableClazz==null){
				this.tableClazz = new TableClazz(tableName);
			}
			
			
			//取子表信息
			List<Map<String, Object>> data = ((SimplePropTableModel) subtable.getModel()).getTableData();
			for (Map<String, Object> row : data) {
				String subTable = (String) row.get("tableName");
				String fkCol = (String) row.get("fkCol");
				if (!"".equals(subTable) &&! "".equals(fkCol)) {
					TableClazz sub = new TableClazz(subTable);
					sub.setFkColumn(fkCol);
					sub.setFatherClazz(tableClazz);
					tableClazz.getSubClazzes().add(sub);
				}
			}
			
			
			//1 实体生成
			//1生成实体
			/*EntityGenerator eg = new EntityGenerator(moduleName);
			EntityTable table = new EntityTable(tableName);	//参数为 表名：tc_pick_after,子表对象：sub
			table.setIdGenerType("uuid");
			eg.generatorModel(table,tableClazz,modelType);*/
			
			//2 SERVICE 代码生成
			/*ServiceDaoGenerator seg = new ServiceDaoGenerator(moduleName);
			seg.generator(tableClazz,params);
			ActionGenerator ag = new ActionGenerator(moduleName);
			ag.generator(tableClazz, params);*/
			
			//3 mxml代码生成
			FlexGenerator fg = new FlexGenerator(moduleName);
			fg.generator(tableClazz, params);
			// TwoTable4GridGenerator2 gener = new
			// TwoTable4GridGenerator2(moduleName);
			// gener.setTemplateStyle(style);
			this.tableClazz.getSubClazzes().clear();
			// gener.generator(main, this.tableClazz);
			
			Runtime.getRuntime().exec("cmd.exe /c start "+ GeneratorProperties.getRequiredProperty("outRoot"));
		} catch (Exception ee) {
			ee.printStackTrace();
			return;
		}
	}
}